<template>
	<view class="localtion">
		<view v-if="showPage">
			<map
			  id="map"   
			  :longitude="location.lote"   
			  :latitude="location.late"   
			  :scale="scale"   
			  show-location   
			  :markers="markers"  
			   style="width: 100%; height: 100vh;">  
			</map>  
		</view>
		<view v-if="isEmptPage">
			<Empt description="暂无定位信息" />
		</view>
		<view class="get-children-localtion" @click="() => queryChildrenLocal()" v-if="showPage">
			获取孩子位置
		</view>
		<view class="footer" v-if="showPage">
			<view class="header">
				<view class="title">{{address}}</view>
				<view class="des-btn">
					<view class="des">
						<view class="gps-tips">GPS 定位有偏差仅供参考（信号弱时偏差大）</view>
						<view class="time">定位时间： {{ location.lastLocTime }}</view>
					</view>
					<view class="btn" @click="() => refresh()">刷新位置</view>
				</view>
			</view>
			<view class="btn-list">
				<view class="safe-site base-btn" @click="() => gotoPage()">安全区域</view>
				<view class="active-trajectory base-btn" @click="jumpPage">活动轨迹</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { computed, onMounted, ref } from 'vue'
	import { homeServer } from "@/common/index";
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import {onShow} from "@dcloudio/uni-app"
	import Empt from "@/components/Empt/index.vue"
	import { mapSdk, location as locationHelp } from '@/utils/index'; 
	import { useBound } from "@/hooks/useBound.ts"
	import gcoord from '@/utils/gcoord.global.prod.js';
	import { useVipStore } from '@/stores/useVip.js'
	import { mock } from "@/utils/index"
		
	const vipStore = useVipStore();
	const {tipBoundStudent, studentIsEmpt} = useBound();
	// import BaseMap from '@/components/baseMap/index.vue'
	const studentStore = useStudentListStore();
	const curStd = computed(() => studentStore.currentStudent);
	const showPage = ref(false)
	const isEmptPage = ref(false)
	const map = ref(null);
	const location = ref({
		lote:"",
		late:""
	});
	// const location = ref({});
	const markers = ref([])
	const scale = ref(13);
	const transformLatLon = (longitude, latitude) => {
		const baiduCoord = [longitude, latitude];
		  // 使用 gcoord 将百度坐标转化为腾讯地图坐标
		const tencentCoord = gcoord.transform(
			baiduCoord,
			gcoord.BD09,  // 百度坐标系
			gcoord.GCJ02  // 腾讯地图使用的是国测局坐标系 (GCJ02)
		);
		return tencentCoord;
	}
	
	const findLocation = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生id')
			return;
		}
		try{
			uni.showLoading({});
			const {status, data} = await homeServer.findLocation({studentId})
			if(status === '200'){
				location.value = data;
				if(data.lote && data.late){
					const [longitude, latitude] = transformLatLon(data.lote, data.late)
					const cb = (address) => {
						const marker = {
							// id: Number(data.studentId),  //必须是number类型
							 id:1,
							 latitude,  
							 longitude,  
							 width: 50,  
							 height: 50,  
							 iconPath: '/static/images/tabbar/postion.png', // 自定义图标路径  
							 callout: {
								// color: "#000000",
							 //    bgColor: "#ffffff", // 添加背景色
								// fontSize:14,
								// textAlign:'center',
								// content: 1,
								// display: 'ALWAYS', 
								// padding: 5  ,
								content: address,
								
								color: "#000000",
								bgColor: "#ffffff",
								borderRadius: 1,
								display: "ALWAYS",
								padding: 5,
								textAlign: "center",
							 }
						}
						console.log('address查询出来的地址', address)
						markers.value = [marker];
						showPage.value = true;
					}
					queryAddreName({latitude: data.late, longitude: data.lote, cb});
				} else {
					isEmptPage.value = true
				}
			}
			uni.hideLoading();
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	const address = ref(""); // 地点
	// 利用经纬度查询地名
	const queryAddreName = ({latitude, longitude, cb = (props) => {}}) => {
		const transformLatLon = (longitude, latitude) => {
			const baiduCoord = [longitude, latitude];
			  // 使用 gcoord 将百度坐标转化为腾讯地图坐标
			const tencentCoord = gcoord.transform(
				baiduCoord,
				gcoord.BD09,  // 百度坐标系
				gcoord.GCJ02  // https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/methodReverseGeocoder
			);
			return tencentCoord;
		}
		const [lon, lat] = transformLatLon(longitude, latitude)
		try{
			mapSdk.QQMapSdk.reverseGeocoder({
				location: {  
				    latitude: lat,  
				    longitude: lon  
				},
				success:(res) => {
					const {status, result} = res;
					console.log('result', result)
					if(status === 0){
						 address.value = result.address
						 cb?.(result?.formatted_addresses?.standard_address || result.address)
					}
					console.log('解析的地址为', res)
				},
				fail: function(res){
					console.log('解析出错-----》', res)
					uni.showToast({
						title:res?.message || '解析出错',
						icon:"none",
						complete() {
							showPage.value = false;
							isEmptPage.value = true
						}
					})
				}
			})
			uni.hideLoading();
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	// 轨迹查询
	const findGatherRecords = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生id')
			return;
		}
		try{
			const {status, data} = await homeServer.findGatherRecords({studentId});
			if(status === '200'){
				console.log('轨迹', data)
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	onShow(() => {
		 findLocation();
		 findGatherRecords();
	})
	
				
		// 设置mock 数据
		const setMock = () => {
			const data = mock.INDEX_LOCATION.data
			console.log("mock 数据", data)
			location.value = data;
			if(data.lote && data.late){
				const [longitude, latitude] = transformLatLon(data.lote, data.late)
				const marker = {
					// id: Number(data.studentId),  //必须是number类型
					 id:1,
					 latitude,  
					 longitude,  
					 width: 50,
					 height: 50,  
					 iconPath: '/static/images/tabbar/postion.png', // 自定义图标路径  
					 callout: {
						content: '体验账号',
						display: 'ALWAYS', 
						padding: 5  
					 }
				}
				queryAddreName({latitude: data.late, longitude: data.lote});
				markers.value = [marker];
				showPage.value = true;
			}
		}
		
	
	onMounted(() => {
		if(!mock.isLogged()){
			showPage.value = true
			setMock()
		}
		map.value = uni.createMapContext('map');
		if(studentIsEmpt.value){
			isEmptPage.value = true
			return;
		 }
		// // 创建map对象
		map.value = uni.createMapContext('map');
		// findLocation();
		// findGatherRecords();
	})
	// 获取孩子位置
	const queryChildrenLocal = async () => {
		try{
			if(vipStore.childrenLocalIsOutTime()){
				uni.showToast({
					title:"下发指令过于频繁，定位会导致孩子手机耗电过高，请19分钟后再操作",
					duration:2000,
					icon:"none"
				})
				return
			} else {
				uni.showModal({
					title:"温馨提示",
					content:"请勿频繁获取孩子的位置，定位会导致孩子手机耗电比较快，建议每日最多下发6次定位，如位置未及时上传（孩子端断网，信号差），请等待，请勿重复发送，谢谢！",
					cancelText:"取消",
					confirmText:"确定",
					success(porps) {
						const {cancel, confirm} = porps;
						if(confirm){
							vipStore.setClickChildrenLocalTimeLimt()
							if(studentIsEmpt.value){
								tipBoundStudent();
								return;
							}
							try{
								homeServer.pushToStudent({studentId: curStd.value?.id})
							}catch(e){
								console.log(e)
								//TODO handle the exception
							}
							
							// locationHelp.getLocation(() => {
							// 	if(studentIsEmpt.value){
							// 		tipBoundStudent();
							// 		return;
							// 	}
							// 	findLocation()	
							// })
						}
						if(cancel){
						   console.log("取消了")
						}
					}
				})
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	const refresh = () => {
		locationHelp.getLocation(() => {
			if(!mock.isLogged()){
				tipBoundStudent();
				return;
			}
			findLocation()	
			uni.showToast({
				title:"刷新成功",
				icon:"success"
			})
			// uni.showModal({
			// 	content:"确认刷新",
			// 	cancelText:"取消",
			// 	confirmText:"刷新",
			// 	success({confirm}) {
			// 		if(confirm){
			// 			if(studentIsEmpt.value){
			// 				tipBoundStudent();
			// 				return;
			// 			}
			// 			findLocation()					
			// 		}
			// 	}
			// })
		});
	}
	
	const jumpPage = () => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return;
		}
		uni.navigateTo({
			url:'/pagesC/trajectory/index'
		})
	}
	
	const gotoPage = () => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return;
		}
		locationHelp.getLocation(() => {
			uni.navigateTo({
				url:`/pagesC/secZone/index?late=${location.value.late}&lote=${location.value.lote}`
			})
		})
	}
	
</script>

<style lang="scss" scoped>
	
	.localtion{
		.get-children-localtion{
			position: fixed;
			z-index: 101;
			right: 50upx;
			bottom: 450upx;
			height: 100upx;
			width: 100upx;
			padding: 10upx;
			background-color: #2BC888;
			border-radius: 50%;
			color: #fff;
			font-size: 25upx;
			text-align: center;
			display: flex;
			align-items: center;
		}
		
		.footer{
			position: fixed;
			z-index: 100;
			left: 20upx;
			right: 20upx;
			bottom: 20upx;
			height: 300upx;
			background-color: #fff;
			border-radius: 10px;
			padding: 40upx 20upx;
			.header{
				.title{
					font-size: 32upx;
					color: #000;
					margin-bottom: 20upx;
				}
				.des-btn{
					display: flex;
					justify-content: space-between;
					align-items: center;
					.des{
						font-size: 22upx;
						color: #636363;
						display: flex;
						justify-content: flex-start;
						flex-direction: column;
						.gps-tips{
							margin-bottom: 10upx;
						}
						.time{}
					}
					.btn{
						width: 200upx;
						height: 50upx;
						line-height: 50upx;
						text-align: center;
						border: 1px solid #2BC888;
						font-size: 30upx;
						color: #2BC888;
						border-radius: 15upx;
					}
				}
			}
			.btn-list{
				display: flex;
				justify-content: space-around;
				margin-top: 80upx;
				.base-btn{
					width: 200upx;
					height: 60upx;
					line-height: 60upx;
					font-size: 28upx;
					color: #3a3838;
					border-radius: 10upx;
					text-align: center;
					border: 1px solid #2BC888;
				}
				.safe-site{
				
				}
				.active-trajectory{
					
				}
			}
		}
	}
</style>